class Word < ActiveRecord::Base
  validates_presence_of :word, :explanation, :creator_id
  validates_uniqueness_of :word, :message=>"单词已经存在", :case_sensitive=>false


  has_many :word_comments do 
    def visible_to_user_id (user_id, word_id)
      if user_id
        find_by_sql (["select * from word_comments where id" + 
          " not in (select word_comments.id from word_comments inner join users_comments on word_comments.id = users_comments.comment_id" + 
        " where users_comments.user_id = ? and users_comments.visible = ?) and word_id = ? order by rating desc limit 5", user_id, false, word_id])
      else  
        find :all, :limit => 5
      end
    end
  end
  belongs_to :creator, :class_name => "User", :foreign_key => "creator_id"
  has_many :bookmarks do 
    def rating_to_user (user_id)
      bookmark = find :first, :conditions => ["user_id = ?", user_id]
      if bookmark == nil
        bookmark = Bookmark.new
        bookmark.rating = 0
      end
      bookmark
    end
  end
  has_many :learners, :class_name => "User", :through => :bookmarks, :source => :user
  def self.search(search, page)
    if search
        # current the search result has only one word
        paginate :all, :per_page => 5, :page=>page, :conditions => ['word == ?', search]
      else
        paginate :per_page => 5, :page => page, :order => 'updated_at, word'
      end
  end
    
end
